import { Injectable, Inject, NotFoundException, StreamableFile } from '@nestjs/common';

import Mime from 'mime-types';
import { PrismaService } from '../common/prisma/prisma.service';
import { PrismaClient, Upload, } from '@/module/common/prisma/client';
import { createReadStream } from 'fs';

@Injectable()
export class DownloadService {

    constructor(
        private readonly prisma: PrismaService
    ) {

    }

    async getFileInfo(id: string): Promise<Upload> {
        const file = await this.prisma.upload.findUnique({
            where: { uploadId: id },
        });

        if (!file) {
            throw new NotFoundException('File not found');
        }

        return file;
    }

    async getFileStream(id: string): Promise<{ stream: StreamableFile; fileInfo: Upload }> {
        const fileInfo = await this.getFileInfo(id);

        if (!fileInfo.url) {
            throw new NotFoundException('File path not found');
        }

        const fileStream = createReadStream('../upload/' + fileInfo.newFileName);

        return {
            stream: new StreamableFile(fileStream, {
                type: Mime.lookup(fileInfo.originalName) || 'application/octet-stream',
                disposition: `attachment; filename="${encodeURIComponent(fileInfo.originalName)}"`
            }),
            fileInfo,
        };
    }
}
